<?php

namespace app\admin\controller\wechat;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use think\Session;
use app\admin\model\HkStore;
use app\admin\model\ConsumeCard;
use think\Db;
use app\mpbase\library\WechatCard;
//use app\api\model\WechatCard as CardModel;

/**
 * 微信卡券
 *
 * @icon fa fa-circle-o
 */
class Card extends Backend
{
    
    /**
     * WechatCard模型对象
     */
    protected $model = null;
    protected $multiFields = ['visible'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('WechatCard');
        $this->view->assign("dateTypeList", $this->model->getDateTypeList());
        $this->view->assign("useCustomCodeList", $this->model->getUseCustomCodeList());
        $this->view->assign("getCustomCodeModeList", $this->model->getGetCustomCodeModeList());
        $this->view->assign("bindOpenidList", $this->model->getBindOpenidList());
        $this->view->assign("canShareList", $this->model->getCanShareList());
        $this->view->assign("canGiveFriendList", $this->model->getCanGiveFriendList());
        $this->view->assign("colorList", $this->model->getColorList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax())
		{
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('pkey_name'))
			{
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			$total = $this->model
				->where($where)
                ->where('card_id','neq',0)
                ->where('status','<>','CARD_STATUS_DELETE')
				->order($sort, $order)
				->count();

			$list = $this->model
                ->with('store')
				->where($where)
                ->where('card_id','neq',0)
				->where('status','<>','CARD_STATUS_DELETE')
				->order($sort, $order)
				->limit($offset, $limit)
				->select();

			$result = array("total" => $total, "rows" => $list);

			return json($result);
		}
		return $this->view->fetch();
	}


    //  添加卡券
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
			$store_info = model('Store')->getInsert($params['store_id']);
            $params['area_id'] = $store_info['area_id'];

            if ($params)
            {
                if ($this->dataLimit)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                // 应用数据限制
                if ($this->appletLimit)
                {
                    $params['appletid'] = $this->appletLimit;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $this->model->init_quantity = $params['quantity'];
                    if(!isset($params['reduce_cost'])){//判断有无最低消费额
                        $params['reduce_cost'] = $params['business_price'];
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $data = [];
                        $card = $this->model->get($this->model->id);
						$card_operate = $this->model->where('id',$this->model->id);
                        $wechatCard = new \app\mpbase\library\WechatCard();
                        $logoResult = $wechatCard->uploadImage('./'.$card['logo_url']);
//                        $imgResult = $wechatCard->uploadImage('./'.$card['thumb_img']);
                        if(!isset($logoResult['url']) || !isset($logoResult['url'])){
							$card_operate->delete();
                            $this->error('图片上传失败');
                        }
                        $card['wechat_logo_url'] = $logoResult['url'];
//                        $data['wechat_logo_url'] = $logoResult['url'];
                        try {
                            $result = $wechatCard->createCard($card['card_type'], $card->getBaseInfo(), $card->getEspecial());
                        }catch(Exception $e){
                            $this->error('卡券创建失败');
                        }
                        if($result['errcode'] == 0 && $result['errmsg'] == 'ok'){
//                            $card->card_id = $result['card_id'];
//                            $card->thumb_url = $logoResult['url'];
//                            $card->allowField(true)->save();
                            $data['card_id'] = $result['card_id'];
                            $data['thumb_url'] = $logoResult['url'];
                            Db::table('uct_wechat_card')
                                ->where(['id' => $this->model->id])
                                ->update($data);
                            $this->success('卡券创建成功');
//                                $this->success();
                        }else{
							$card_operate->delete();
                            $this->error($result);
                        }
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//		//获取该管理员的店铺id
		$storeList = model('HkStore')->storeList();
		//使用类型列表
		$useList = $this->model->useList();
		//卡券的分类
        $catList = Db::table('uct_store_cat')->column('id','cat_name');
		//百米平台选择区域
        $areaList = Db::table('uct_card_area')->select();
        $this->view->assign('areaList',$areaList);
		$this->view->assign('storeList',$storeList);
        $this->view->assign('useList',$useList);
        $this->view->assign('catList',$catList);
        return $this->view->fetch();
    }


    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $wechatCard = new \app\mpbase\library\WechatCard();
                        $imgResult = $wechatCard->uploadImage('./'.$row['thumb_img']);
                        if(!isset($imgResult['url'])){
                            $row->delete();
                            $this->error('图片上传失败');
                        }
                        $row->thumb_url = $imgResult['url'];
                        $row->allowField(true)->save();
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


	public function group($ids=null)
	{
		$row = $this->model->get($ids);
		if (!$row)
			$this->error(__('No Results were found'));
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds))
		{
			if (!in_array($row[$this->dataLimitField], $adminIds))
			{
				$this->error(__('You have no permission'));
			}
		}
//		$groupList = model('CardGroup')->where(['status'=>'normal'])->value('id','group_name');
//		$groupList = model('CardGroup')->where(['status'=>'normal'])->select();
        $groupList = model('CardGroup')->order('status asc')->select();
		if ($this->request->isPost())
		{
			$params = $this->request->post("row/a");
			if ($params)
			{
				/*
				 * 已经弃用,如果为了兼容老版可取消注释
				  foreach ($params as $k => &$v)
				  {
				  $v = is_array($v) ? implode(',', $v) : $v;
				  }
				 */
				try
				{
                    //将卡券加入到主题中
					$group = model('CardGroup')->where('id',$params['group_id'])->find();
                    $card_id = $row->id;
					$card_ids = explode(',',$group->card_ids);
					if(in_array($card_id,$card_ids)){
                        //存在ids中
						$this->error('该卡券已存在主题内');
					}else{
						//不存在ids中
						$group->card_ids = $group->card_ids.','.$card_id;
						$result = $group->save();
					}
					if ($result !== false)
					{
						$this->success();
					}
					else
					{
						$this->error($row->getError());
					}
				}
				catch (\think\exception\PDOException $e)
				{
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$this->view->assign("row", $row);
		$this->view->assign('groupList',$groupList);
		return $this->view->fetch();
	}

    //  删除卡券
    public function del($ids = "")
    {
        if ($ids)
        {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v)
            {
                //判断该卡券是否已经是删除状态
                if($v['status'] == 'CARD_STATUS_DELETE'){
                    $this->error(__('卡券已经删除'));
                }
                $wechatCard = new \app\mpbase\library\WechatCard();
                $result = $wechatCard->delete($v['card_id']);
                if($result['errcode'] == 0 && $result['errmsg'] == 'ok')
				{
				    if(session('admin.type') == 2){
                        //删除卡券，广告位余额需要同步

                        //初始金额
                        $init = $v['init_quantity'] * $v['business_price'];
                        $banlance = Db::table('uct_wechat_card')->alias('card')
                            ->join('uct_consume_card consume','card.card_id = consume.card_id')
                            ->where(['card.card_id' => $v['card_id']])
                            ->sum('business_price');
                        $banlance = $init - $banlance;
                        Db::table('uct_hk_store')->where(['id' => $v['store_id']])->setInc('banlance',$banlance);
                    }
//					$del = $this->model->where($pk,$v->id)->delete();
                    //修改卡券删除status,改变status状态后删除图
                    $update = $this->model->where($pk,$v->id)->update(['status' => 'CARD_STATUS_DELETE']);
				    unlink('.'.$v['logo_url']);
				    Db::table('uct_attachment')->where(['url' => $v['logo_url']])->delete();
					$count += $update;
				}
            }
            if ($count)
            {
                $this->success();
            }
            else
            {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //同步
    public function synch()
    {
//        $wechatCard = new \app\mpbase\library\WechatCard();
//        $res = $wechatCard->synchData();
//        $this->success('同步完成:'.$res.'条记录');

        $time = 1527696001;
        $admin_id = session('admin.id');
        $card_list = $this->model->where('status','<>','CARD_STATUS_DELETE')
            ->where('end_timestamp','<',$time)
            ->where('card_id','<>',0)
            ->select();

        $wechatCard = new \app\mpbase\library\WechatCard();
        $count = 0;
        foreach($card_list as $key => $val){
            $result = $wechatCard->delete($val['card_id']);
            if($result['errcode'] == 0 && $result['errmsg'] == 'ok'){//判断微信后台端是否正确删除
                Db::startTrans();
                try {
                    //初始金额
                    $init = $val['init_quantity']*$val['business_price'];
                    $banlance = Db::table('uct_wechat_card')->alias('card')
                        ->join('uct_consume_card consume','card.card_id = consume.card_id')
                        ->where(['card.card_id' => $val['card_id']])
                        ->sum('business_price');
                    $banlance = $init - $banlance;
                    Db::table('uct_hk_store')->where(['id' => $val['store_id']])->setInc('banlance', $banlance);
                    //修改卡券删除status
                    $update = $this->model->where('id', $val->id)->update(['status' => 'CARD_STATUS_DELETE']);
                    unlink('.'.$val['logo_url']);
                    Db::table('uct_attachment')->where(['url' => $val['logo_url']])->delete();
                    $count += $update;
                    Db::commit();
                }catch(\Exception $e){
                    Db::rollback();
                }
            }
        }
        $this->success('同步卡券数'.$count);
    }

    //生成卡券二维码
	public function qrCode($ids="")
	{
        if($ids){
	        $wechatCard = new \app\mpbase\library\WechatCard();
			$res = $wechatCard->qrCode($ids);
            if(isset($res['msg'])){
				$this->error($res['msg']);
			}
			$this->view->assign('res',$res);
            return $this->view->fetch();
		}
		$this->error(__('Parameter %s can not be empty', 'ids'));
	}

	//审核请求
	public function cardinfo($ids="")
    {
          $num = $this->model->requestCard($ids);
          $this->success('审核卡券');
    }

	//分类类
	public function selectpage()
	{
		return parent::selectpage();
	}


	public function test()
	{
        $banlance = Db::table('uct_wechat_card')->alias('card')
            ->join('uct_consume_card consume','card.card_id = consume.card_id')
            ->where(['card.card_id' => 'p7EQD1gh3CHbJqpR633GuFPWIwms'])
            ->sum('business_price');
        dump($banlance);
	}
//	public function gettoken()
//	{
//		$wechatCard = new \app\mpbase\library\WechatCard();
//		$qrcode = $wechatCard->qrcode;
//	}
}
